/*
 *  Copyright 2019-2025 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.server.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.dao.*;
import me.zhengjie.dao.dto.InventoryTaskQueryCriteria;
import me.zhengjie.enums.ConstantStatus;
import me.zhengjie.enums.InboundStatusEnum;
import me.zhengjie.mapper.InventoryTaskMapper;
import me.zhengjie.network.WcsNetworkRequest;
import me.zhengjie.server.*;
import me.zhengjie.utils.*;
import me.zhengjie.vo.Inbound.MesMaterialVo;
import me.zhengjie.vo.Inventory.*;
import me.zhengjie.vo.OutBoundTaskToWcsVo;
import me.zhengjie.vo.Result;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author laoxu
 * @description 服务实现
 * @date 2025-06-26
 **/
@Service
@RequiredArgsConstructor
public class InventoryTaskServiceImpl extends ServiceImpl<InventoryTaskMapper, InventoryTaskDao> implements InventoryTaskService {

    private static final Logger inventoryLog = LoggerFactory.getLogger("inventory");

    private final InventoryTaskMapper inventoryTaskMapper;

    private final MaterialService materialService;

    private final StoreOutsideService storeOutsideService;

    private final TransactionTemplate transactionTemplate;

    private final InventoryTaskRecordService inventoryTaskRecordService;

    @Override
    public PageResult<InventoryTaskDao> queryAll(InventoryTaskQueryCriteria criteria, Page<Object> page) {
        return PageUtil.toPage(inventoryTaskMapper.findAll(criteria, page));
    }

    @Override
    public List<InventoryTaskDao> queryAll(InventoryTaskQueryCriteria criteria) {
        return inventoryTaskMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(InventoryTaskDao resources) {
        inventoryTaskMapper.insert(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(InventoryTaskDao resources) {
        InventoryTaskDao inventoryTaskDao = getById(resources.getId());
        inventoryTaskDao.copy(resources);
        inventoryTaskMapper.updateById(inventoryTaskDao);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<String> ids) {
        inventoryTaskMapper.deleteBatchIds(ids);
    }

    @Override
    public void download(List<InventoryTaskDao> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (InventoryTaskDao inventoryTaskDao : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("任务单号", inventoryTaskDao.getTaskId());
            map.put("任务状态", inventoryTaskDao.getTaskStatus());
            map.put("盘点类型（全盘，抽盘，动碰盘）", inventoryTaskDao.getInventoryType());
            map.put("载具状态", inventoryTaskDao.getContainerStatus());
            map.put("任务起点储位", inventoryTaskDao.getTaskStart());
            map.put("任务终点储位", inventoryTaskDao.getTaskEnd());
            map.put("载具码", inventoryTaskDao.getContainerCode());
            map.put("仓库", inventoryTaskDao.getFloor());
            map.put("建单账号", inventoryTaskDao.getCreateName());
            map.put("建单时间", inventoryTaskDao.getCreateDate());
            map.put("开始时间", inventoryTaskDao.getStartDate());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Page<InventoryTaskDao> findInventoryTaskData(InventoryTaskQueryCriteria criteria) {
        Page<InventoryTaskDao> page = new Page<>(criteria.getPage(), criteria.getSize());
        return inventoryTaskMapper.findInventoryTaskData(page, criteria);
    }

    @Override
    public Page<ContainerExtractVo> findAvailableExtractData(InventoryExtractBaseVo baseVo) {
        Page<ContainerExtractVo> page = new Page<>(baseVo.getPage(), baseVo.getSize());
        try {

            Page<ContainerExtractVo> availableData = inventoryTaskMapper.findAvailableExtractData(page, baseVo);
            for (ContainerExtractVo record : availableData.getRecords()) {
                String[] itemBarCodeList = record.getItemBarCodeList().split(",");
                List<String> list = Arrays.asList(itemBarCodeList);
                List<MaterialDao> barCodeList = materialService.findDataList(list);
                record.setMaterialList(barCodeList);
            }
            return availableData;
        }catch (Exception e){
            page.setRecords(new ArrayList<>());
            return page;
        }
    }

    @Override
    public Page<ContainerMoveVo> findAvailableMoveData(InventoryMoveBaseVo baseVo) {
        Page<InventoryMoveBaseVo> page = new Page<>(baseVo.getPage(), baseVo.getSize());
        return inventoryTaskMapper.findAvailableMoveData(page, baseVo);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> createInventorySheet(CreateInventoryVo createVo) {
        if (createVo == null) {
            return Result.error("创建盘点任务失败，请输入完整的盘点信息");
        }
        String inventoryType = createVo.getInventoryType();
        String workIp = createVo.getWorkIp();
        String floor = createVo.getFloor();
        String goodType = createVo.getGoodType();
        if (inventoryType == null || workIp == null || floor == null || goodType == null) {
            return Result.error("创建盘点任务失败，请输入完整的盘点信息");
        }

        List<CreateInventoryVo.CreateBuilder> createBuilderList = createVo.getMaterialList();
        String taskId = String.valueOf(SnowIdUtil.nextId());
        Timestamp createDate = new Timestamp(System.currentTimeMillis());
        List<InventoryTaskDao> InventoryTaskList = new ArrayList<>();
        for (CreateInventoryVo.CreateBuilder createBuilder : createBuilderList) {
            String containerCode = createBuilder.getContainerCode();
            String storeId = createBuilder.getStoreId();

            if (containerCode == null || storeId == null) {
                return Result.error("创建盘点任务失败，请输入完整的盘点信息");
            }
            // 根据载具编码获取要物料信息
            List<MaterialDao> materialDaoList = materialService
                    .findDataDao(new MaterialDao().setContainerCode(containerCode));
            for (MaterialDao materialDao : materialDaoList) {
                InventoryTaskDao taskDao = new InventoryTaskDao();
                // 任务id
                taskDao.setId(String.valueOf(SnowIdUtil.nextId()));
                taskDao.setTaskId(taskId);
                // 盘点类型状态
                taskDao.setTaskStatus(ConstantStatus.INVENTORY_TO_BE);
                taskDao.setInventoryType(inventoryType);
                // 载具状态
                taskDao.setContainerStatus(ConstantStatus.CONTAINER_TO_BE);
                taskDao.setContainerCode(containerCode);
                // 物料信息
                taskDao.setEntryTime(materialDao.getEntryTime());
                taskDao.setItemBarCode(materialDao.getItemBarCode());
                taskDao.setMaterialCode(materialDao.getMaterialCode());
                taskDao.setMaterialName(materialDao.getMaterialName());
                taskDao.setInventoryQuantity(materialDao.getInventoryQuantity());
                // 开始地址
                taskDao.setTaskStart(storeId);
                // 出库地址
                taskDao.setWorkIp(workIp);
                taskDao.setFloor(floor);
                taskDao.setGoodType(goodType);
                // 创建人信息
                taskDao.setCreateName(createVo.getCreateName());
                taskDao.setCreateDate(createDate);
                InventoryTaskList.add(taskDao);
            }
        }
        boolean result = this.saveBatch(InventoryTaskList);
        if (result) {
            return Result.success("创建盘点任务成功");
        } else {
            return Result.error("创建盘点任务失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> startInventoryTask(String startName, String taskId) {
        LambdaQueryWrapper<InventoryTaskDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InventoryTaskDao::getTaskId, taskId);
        wrapper.eq(InventoryTaskDao::getTaskStatus, ConstantStatus.INVENTORY_ING);
        if (this.count(wrapper) > 0) {
            return Result.error("盘点任务已开始");
        }
        LambdaUpdateWrapper<InventoryTaskDao> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(InventoryTaskDao::getTaskId, taskId);
        updateWrapper.set(InventoryTaskDao::getTaskStatus, ConstantStatus.INVENTORY_ING);
        updateWrapper.set(InventoryTaskDao::getStartName, startName);
        updateWrapper.set(InventoryTaskDao::getStartDate, new Timestamp(System.currentTimeMillis()));
        boolean update = this.update(updateWrapper);
        if (update) {
            // this.outBoundInventoryTask(taskId);
            return Result.success("盘点任务开始");
        }
        return Result.error("盘点任务开始失败");
    }

    @Override
    public Result<?> outBoundInventoryTask() {
        //查询任务单
        LambdaQueryWrapper<InventoryTaskDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(InventoryTaskDao::getContainerCode)
                .eq(InventoryTaskDao::getContainerStatus, ConstantStatus.CONTAINER_TO_BE)
                .eq(InventoryTaskDao::getTaskStatus, ConstantStatus.INVENTORY_ING)
                .groupBy(InventoryTaskDao::getContainerCode);
        List<InventoryTaskDao> inventoryTaskList = this.list(wrapper);

        if (inventoryTaskList.isEmpty()) {
            return Result.error("任务单不存在");
        }
        while (!inventoryTaskList.isEmpty()) {
            for (InventoryTaskDao inventoryTaskDao : inventoryTaskList) {
                // 货位信息
                String goodType = inventoryTaskDao.getGoodType();
                // 楼层信息
                String floor = inventoryTaskDao.getFloor();
                // 工位IP
                String workIp = inventoryTaskDao.getWorkIp();
                // 查询储位信息
                List<String> storeIdList = new ArrayList<>();
                storeOutsideService.findAvailableStoreIdList(null, workIp, floor, goodType, storeIdList);
                if (storeIdList.isEmpty()) {
                    continue;
                }
                String outStoreId = storeIdList.get(0);
                // 更改任务单信息
                inventoryTaskDao.setTaskEnd(outStoreId);
                inventoryTaskDao.setContainerStatus(ConstantStatus.CONTAINER_OUTBOUND_ING);
                try {
                    this.InventoryExecuteTransactional(inventoryTaskDao);
                } catch (Exception e) {
                    inventoryLog.error("{}   {}", Thread.currentThread().getName(), e.getMessage());
                }
            }
            inventoryTaskList = this.list(wrapper);
        }
        return Result.success("出库成功");
    }

    @Override
    public Result<?> inventoryScanContainer(String containerCode) {
        List<InventoryTaskDao> taskList =
                this.queryAll(new InventoryTaskQueryCriteria().setContainerCode(containerCode));
        return Result.success(taskList);
    }

    @Override
    public Result<?> inventoryScanMaterial(String containerCode, String itemBarCode) {
        MaterialDao materialDao = materialService.findDataOne(itemBarCode);
        if (containerCode.equals(materialDao.getContainerCode())) {
            LambdaUpdateWrapper<InventoryTaskDao> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(InventoryTaskDao::getContainerCode, containerCode);
            wrapper.eq(InventoryTaskDao::getItemBarCode, itemBarCode);
            wrapper.set(InventoryTaskDao::getTaskStatus, ConstantStatus.INVENTORY_COMPLETED);
            boolean update = this.update(wrapper);
            if (update) {
                return new Result<>(200, "该物料条码在盘点载具中", materialDao);
            } else {
                return Result.error("盘点失败");
            }
        }
        if (materialDao.getMaterialCode() != null) {
            return new Result<>(204, "该物料条码绑定在其他载具中", materialDao);
        } else {
            return new Result<>(205, "该物料未绑定其他载具", null);
        }
    }

    @Override
    public Result<?> bingMaterialToContainerCode(String containerCode, String itemBarCode) {
        List<String> itemBarCodeList = new ArrayList<>();
        itemBarCodeList.add(itemBarCode);
        MaterialDao materialDao = new MaterialDao().setContainerCode(containerCode);
        boolean result = materialService.updateDataByList(itemBarCodeList, materialDao);
        if (result) {
            return Result.success("绑定成功");
        } else {
            return Result.error("绑定失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> inventoryUpdateQuantity(String itemBarCode, Double quantity) {
        if (quantity == null || quantity == 0.0) {
            return Result.error("数量不能为空");
        }
        List<String> itemBarCodeList = new ArrayList<>();
        itemBarCodeList.add(itemBarCode);
        MaterialDao materialDao = new MaterialDao()
                .setInventoryQuantity(quantity).setAbnormal("1");
        boolean result = materialService.updateDataByList(itemBarCodeList, materialDao);

        LambdaUpdateWrapper<InventoryTaskDao> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(InventoryTaskDao::getItemBarCode, itemBarCode);
        wrapper.set(InventoryTaskDao::getInventoryQuantity, quantity);
        wrapper.set(InventoryTaskDao::getTaskStatus, ConstantStatus.INVENTORY_ABNORMAL);
        boolean update = this.update(wrapper);

        if (result && update) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    @Override
    public PageResult<InventoryDetailsVo> findInventoryTaskDetails(String taskId, Integer page, Integer size, String materialCode, String containerCode, Integer taskStatus) {
        Page<Object> pageCount = new Page<>(page, size);
        IPage<InventoryDetailsVo> materialByDao = inventoryTaskMapper.findMaterialByCode(taskId, materialCode, containerCode, taskStatus, pageCount);
        PageResult<InventoryDetailsVo> pageResult = new PageResult<>();
        pageResult.setContent(materialByDao.getRecords());
        pageResult.setTotalElements(materialByDao.getTotal());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateContainerStatusByCode(String containerCode, Integer status) {
        LambdaUpdateWrapper<InventoryTaskDao> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(InventoryTaskDao::getContainerCode, containerCode);
        wrapper.set(InventoryTaskDao::getContainerStatus, status);
        this.update(wrapper);
    }

    @Override
    public InventoryTaskDao findInventoryTaskByContainerCode(String containerCode) {
        LambdaQueryWrapper<InventoryTaskDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InventoryTaskDao::getContainerCode, containerCode);
        return this.getOne(wrapper);
    }

    @Override
    public List<InventoryTaskDao> findInventoryTaskByTaskId(String taskId) {
        LambdaQueryWrapper<InventoryTaskDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InventoryTaskDao::getTaskId, taskId);
        return this.list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> reportMissing(String itemBarCode) {
        LambdaUpdateWrapper<MaterialDao> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(MaterialDao::getItemBarCode, itemBarCode);
        wrapper.set(MaterialDao::getAbnormal, "1");
        boolean update = materialService.update(wrapper);

        LambdaUpdateWrapper<InventoryTaskDao> inventoryWrapper = new LambdaUpdateWrapper<>();
        inventoryWrapper.eq(InventoryTaskDao::getItemBarCode, itemBarCode);
        inventoryWrapper.set(InventoryTaskDao::getTaskStatus, ConstantStatus.INVENTORY_ABNORMAL);
        boolean inventoryUpdate = this.update(inventoryWrapper);

        if (update && inventoryUpdate) {
            return Result.success("上报成功");
        }
        return Result.error("上报失败");
    }

    @Override
    public Result<?> inventoryCompleteMaterial(String containerCode) {
        try {
            Result<?> result = this.InventoryInExecuteTransactional(containerCode);
            if (result.getCode() != 200) {
                return Result.error((String) result.getData());
            }
        } catch (Exception e) {
            return Result.error("盘点失败: " + e.getMessage());
        }
        return Result.success("盘点完成成功");
    }

    @Override
    public Result<?> findExistTask() {
        LambdaQueryWrapper<InventoryTaskDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(InventoryTaskDao::getTaskId, InventoryTaskDao::getTaskStatus);
        wrapper.groupBy(InventoryTaskDao::getTaskId).groupBy(InventoryTaskDao::getTaskStatus);
        List<InventoryTaskDao> inventoryTaskDaoList = baseMapper.selectList(wrapper);
        boolean flag = false;
        for (InventoryTaskDao inventoryTaskDao : inventoryTaskDaoList) {
            if (inventoryTaskDao.getTaskStatus() == null){
                continue;
            }
            if (!inventoryTaskDao.getTaskStatus().equals(ConstantStatus.INVENTORY_COMPLETED)) {
                flag = true;
                break;
            }
        }
        return Result.success(flag);
    }

    /**
     * 盘点更新储位-任务单信息-调用WCS出库
     *
     * @param inventoryTaskDao 盘点任务单
     */
    public void InventoryExecuteTransactional(InventoryTaskDao inventoryTaskDao) {
        // 创建出库AGV对象
        // 接口调用失败，标记事务回滚
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(@NotNull TransactionStatus status) {
                try {
                    String outStoreId = inventoryTaskDao.getTaskEnd();
                    String goodType = inventoryTaskDao.getGoodType();
                    if (outStoreId == null || goodType == null) {
                        return;
                    }
                    StoreOutsideService storeOutsideService = SpringContextUtil.getBean(StoreOutsideService.class);
                    InventoryTaskService inventoryTaskService = SpringContextUtil.getBean(InventoryTaskService.class);
                    // 修改目的储位状态
                    StoreOutsideDao storeOutsideDao = new StoreOutsideDao()
                            .setId(outStoreId)
                            .setStatus(InboundStatusEnum.INBOUND_LOCK.status);
                    storeOutsideService.updateData(storeOutsideDao);
                    // 修改任务单信息
                    inventoryTaskService.update(inventoryTaskDao);
                    // 创建出库AGV对象
                    OutBoundTaskToWcsVo task = new OutBoundTaskToWcsVo()
                            .setContainerCode(inventoryTaskDao.getContainerCode())
                            .setSource(inventoryTaskDao.getTaskStart())
                            .setDestination(inventoryTaskDao.getTaskEnd())
                            .setPriority(1)
                            .setFloor(inventoryTaskDao.getFloor())
                            .setDeliveryType(ConstantStatus.InBound_Delivery_Type)
                            .setTaskType(ConstantStatus.Stock_OutBound_Type);
                    // 调用WCS接口
                    WcsNetworkRequest.deliveryTask(task);
                } catch (Exception e) {
                    // 接口调用失败，标记事务回滚
                    status.setRollbackOnly();
                }
            }
        });
    }

    /**
     * 盘点更新储位-任务单信息-调用WCS回库
     *
     * @param containerCode 载具编码
     */
    public Result<?> InventoryInExecuteTransactional(String containerCode) {
        return transactionTemplate.execute(status -> {
            try {
                InventoryTaskService inventoryTaskService = SpringContextUtil.getBean(InventoryTaskService.class);
                InventoryTaskRecordService inventoryTaskRecordService = SpringContextUtil.getBean(InventoryTaskRecordService.class);
                MaterialService materialService = SpringContextUtil.getBean(MaterialService.class);
                InboundService inboundService = SpringContextUtil.getBean(InboundService.class);

                // 查询该载具盘点物料信息
                LambdaQueryWrapper<InventoryTaskDao> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(InventoryTaskDao::getContainerCode, containerCode);
                List<InventoryTaskDao> taskDaoList = baseMapper.selectList(wrapper);
                if (taskDaoList.isEmpty()) {
                    throw new RuntimeException("该载具没有盘点物料信息");
                }
                InventoryTaskDao taskDao = taskDaoList.get(0);

                // 根据载具编码获取要物料信息
                List<MaterialDao> materialDaoList = materialService
                        .findDataDao(new MaterialDao().setContainerCode(containerCode));
                MesMaterialVo mesMaterialVo = new MesMaterialVo()
                        .setData(materialDaoList)
                        .setContainerCode(containerCode)
                        .setNest(true)
                        .setFloor(taskDao.getFloor());

                // 获取回库储位编码
                Result<String> applyStore = inboundService.InboundStorageApply(mesMaterialVo);
                if (applyStore.getCode() != 200) {
                    // 接口调用失败，标记事务回滚
                    status.setRollbackOnly();
                    // 抛出自定义异常，携带错误信息
                    throw new RuntimeException(applyStore.getMessage());
                }

                String taskId = taskDao.getTaskId();
                // 写入到盘点记录表中
                List<InventoryTaskRecordDao> inventoryTaskRecordList = new ArrayList<>();
                for (InventoryTaskDao inventory : taskDaoList) {
                    InventoryTaskRecordDao inventoryTaskRecordDao = new InventoryTaskRecordDao();
                    BeanUtil.copyProperties(inventory, inventoryTaskRecordDao, CopyOptions.create().setIgnoreNullValue(true));
                    inventoryTaskRecordDao.setMaterialCode(inventory.getMaterialCode());
                    inventoryTaskRecordDao.setMaterialName(inventory.getMaterialName());
                    inventoryTaskRecordDao.setCompleteDate(new Timestamp(System.currentTimeMillis()));
                    inventoryTaskRecordList.add(inventoryTaskRecordDao);
                }
                inventoryTaskRecordService.saveBatch(inventoryTaskRecordList);

                // 根据载具编码更新载具状态
                LambdaUpdateWrapper<InventoryTaskDao> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(InventoryTaskDao::getContainerCode, containerCode);
                updateWrapper.set(InventoryTaskDao::getTaskStart, taskDao.getTaskEnd());
                updateWrapper.set(InventoryTaskDao::getTaskEnd, applyStore.getData());
                updateWrapper.set(InventoryTaskDao::getContainerStatus, ConstantStatus.CONTAINER_MERGE_COMPLETED);
                updateWrapper.set(InventoryTaskDao::getStartDate, new Timestamp(System.currentTimeMillis()));
                inventoryTaskService.update(updateWrapper);

                // 查询该任务单是否全部完成
                boolean isComplete = true;
                List<InventoryTaskDao> taskList = inventoryTaskService.findInventoryTaskByTaskId(taskId);
                for (InventoryTaskDao inventoryTaskDao : taskList) {
                    if (!inventoryTaskDao.getContainerStatus().equals(ConstantStatus.CONTAINER_MERGE_COMPLETED)) {
                        isComplete = false;
                        break;
                    }
                }
                if (isComplete) {
                    // 根据任务单号更新任务状态
                    LambdaUpdateWrapper<InventoryTaskDao> InventoryTaskWrapper = new LambdaUpdateWrapper<>();
                    InventoryTaskWrapper.eq(InventoryTaskDao::getTaskId, taskId);
                    InventoryTaskWrapper.set(InventoryTaskDao::getTaskStatus, ConstantStatus.INVENTORY_COMPLETED);
                    inventoryTaskService.update(updateWrapper);
                }

                String floor = taskDao.getFloor();
                // 创建出库AGV对象
                OutBoundTaskToWcsVo task = new OutBoundTaskToWcsVo()
                        .setContainerCode(taskDao.getContainerCode())
                        .setSource(taskDao.getTaskStart())
                        .setDestination(taskDao.getTaskEnd())
                        .setPriority(1)
                        .setFloor(floor)
                        .setDeliveryType(ConstantStatus.Return_Delivery_Type)
                        .setTaskType(ConstantStatus.Stock_RetBound_Type);
                // 调用WCS接口
                Result<?> result = WcsNetworkRequest.deliveryTask(task);
                if (result.getCode() != 200) {
                    throw new RuntimeException(result.getMessage());
                }
                return Result.success();
            } catch (Exception e) {
                // 接口调用失败，标记事务回滚
                status.setRollbackOnly();
                throw e;
            }
        });
    }
}